<template>
  <div class="flex flex-col h-full">
    <!--    <vxe-card title="" class="w-full" :border="false">-->
    <!--      <div class="flex items-center">-->
    <!--        <div class="border-arrow" @click="toPrevPage">-->
    <!--          <FontIcon icon="icon-left" />-->
    <!--        </div>-->
    <!--        <div class="text-[#242930] ml-4">-->
    <!--          {{ t("person_manage.detail.add_person") }}-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </vxe-card>-->

    <vxe-card title="" class="w-full" :border="false" :padding="false">
      <div class="p-[20px]">
        <!--        基本信息       -->
        <div :class="TITLE_CLASS">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("person_manage.detail.basic_info") }}
            </div>
          </div>
        </div>
        <el-descriptions :column="2" border class="desc-item mb-[20px]">
          <el-descriptions-item
            v-for="item in keyDescription"
            :key="item.key"
            label-align="right"
          >
            <template #label>
              <div :class="['cell-item', item.required ? 'required' : '']">
                {{ t(item.name) }}：
              </div>
            </template>
            <el-tree-select
              v-if="item.key === 'address'"
              v-model="personInfo[item.key]"
              :data="provinceList"
              filterable
              style="width: 200px"
            />
            <el-date-picker
              v-else-if="item.key === 'birthday'"
              v-model="personInfo[item.key]"
              :placeholder="t('person_manage.detail.select_start_time')"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px"
            />
            <AuSelect
              v-else-if="item.key === 'gender'"
              v-model="personInfo[item.key]"
              :placeholder="
                t('person_manage.detail.select_required', {
                  name: t(item.name)
                })
              "
              :options="[
                {
                  id: 'M',
                  name: t('person_manage.form.male')
                },
                {
                  id: 'F',
                  name: t('person_manage.form.female')
                }
              ]"
              valueKey="id"
              labelKey="name"
              style="width: 200px"
            />
            <el-input
              v-else
              v-model="personInfo[item.key]"
              :maxlength="item.key === 'addressDetail' ? 100 : 30"
              :placeholder="
                t('person_manage.detail.input_required', { name: t(item.name) })
              "
              :style="{
                width: item.key === 'addressDetail' ? '100%' : '200px'
              }"
            />
          </el-descriptions-item>
        </el-descriptions>

        <!--        入职信息       -->
        <div :class="TITLE_CLASS">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("person_manage.detail.onboarding_info") }}
            </div>
          </div>
        </div>
        <el-descriptions :column="2" border class="desc-item">
          <el-descriptions-item
            v-for="item in keyOnboarding"
            :key="item.key"
            label-align="right"
          >
            <template #label>
              <div
                v-if="item.key"
                :class="['cell-item', item.required ? 'required' : '']"
              >
                {{ t(item.name) }}：
              </div>
            </template>
            <div v-if="!item.key" />
            <AuSelect
              v-else-if="item.key === 'storeId'"
              v-model="personInfo[item.key] as string"
              :placeholder="
                t('person_manage.detail.select_required', {
                  name: t(item.name)
                })
              "
              :options="storeList"
              valueKey="id"
              labelKey="name"
              :filterable="true"
              style="width: 200px"
            />

            <el-date-picker
              v-else-if="item.key === 'onboardingDate'"
              v-model="personInfo[item.key] as string"
              :placeholder="
                t('person_manage.detail.select_required', {
                  name: t(item.name)
                })
              "
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px"
            />
            <div v-else-if="item.key === 'expiryStart'">
              <el-date-picker
                v-model="personInfo[item.key] as string"
                class="mr-[6px]"
                :placeholder="t('person_manage.detail.select_start_time')"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 48%"
              />
              <el-date-picker
                v-model="personInfo['expiryEnd'] as string"
                :placeholder="t('person_manage.detail.select_end_time')"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 48%"
              />
            </div>
            <div v-else-if="item.key === 'empDocs'" class="flex justify-around">
              <el-upload
                v-for="keyItem in item.keys"
                :key="keyItem.key"
                :show-file-list="false"
                accept="image/*"
                class="upload-empDocs w-[24%]"
                action="/autata/file/upload"
                :data="{ foldername: 'person' }"
                @success="e => onSuccess(e, keyItem.key)"
              >
                <img
                  v-if="personInfo[keyItem.key]"
                  :src="handleImgURL(personInfo[keyItem.key])"
                  class="h-full"
                  :alt="t(keyItem.name)"
                />
                <div v-else class="text-center">
                  <FontIcon icon="icon-upload" />
                  {{ t(keyItem.name) }}
                </div>
              </el-upload>
            </div>
            <el-input
              v-else
              v-model="personInfo[item.key]"
              :maxlength="30"
              :placeholder="
                t('person_manage.detail.input_required', { name: t(item.name) })
              "
              :style="{
                width: item.key === 'addressDetail' ? '100%' : '200px'
              }"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div
        class="flex items-center justify-end mt-[16px] px-[20px] py-[10px] border-t border-[--autata-border-color]"
      >
        <el-button @click="cancel">{{ t("buttons.cancel") }} </el-button>
        <el-button type="primary" @click="confirm"
          >{{ t("buttons.confirm") }}
        </el-button>
      </div>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import AuSelect from "@/components/AuForm/src/select.vue";
import { getProvinceCity, ResultProps } from "@/api/user";
import { getStoreList } from "@/api/teaInfuser/store";
import {
  getPersonList,
  personAdd,
  PersonProp,
  personUpd
} from "@/api/expiry/person";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { userKey } from "@/utils/auth";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "expiryMaterialDetail"
});

// region 声明ref变量集合
const TITLE_CLASS = "flex items-center justify-between pb-[16px]";
const router = useRouter();
const route = useRoute();
const proxyPath = import.meta.env?.VITE_PROXY_PATH ?? "/";
const { t } = useI18n();

const keyDescription = [
  { key: "name", name: "person_manage.detail.employee_name", required: true },
  { key: "personNo", name: "person_manage.detail.employee_no" },
  { key: "gender", name: "person_manage.detail.employee_gender" },
  { key: "ethnicity", name: "person_manage.detail.ethnicity" },
  { key: "phone", name: "person_manage.detail.phone", required: true },
  { key: "idCard", name: "person_manage.detail.id_card", required: true },
  { key: "education", name: "person_manage.detail.education" },
  { key: "birthday", name: "person_manage.detail.birthday" },
  { key: "address", name: "person_manage.detail.residence_area" },
  { key: "addressDetail", name: "person_manage.detail.detailed_address" }
];
const keyOnboarding = [
  { key: "department", name: "person_manage.detail.department" },
  { key: "post", name: "person_manage.detail.position" },
  { key: "onboardingDate", name: "person_manage.detail.onboarding_date" },
  { key: "storeId", name: "person_manage.detail.assigned_store" },
  {
    key: "expiryStart",
    name: "person_manage.detail.health_cert_valid_period",
    required: true
  },
  { key: "", name: "" },
  {
    key: "empDocs",
    name: "person_manage.detail.onboarding_materials",
    required: true,
    keys: [
      {
        key: "healthFrontUrl",
        name: "person_manage.detail.health_cert_front",
        required: true
      },
      {
        key: "healthBackUrl",
        name: "person_manage.detail.health_cert_back",
        required: true
      },
      { key: "idCardFrontUrl", name: "person_manage.detail.id_card_front" },
      { key: "idCardBackUrl", name: "person_manage.detail.id_card_back" }
    ]
  }
];
const personInfo = ref<Partial<PersonProp>>({});

const { proxy } = getCurrentInstance();

const storeList = ref([]);
const provinceList = ref([]);

// endregion

// region 公共方法的集合

function init() {
  getProvinceCity().then(res => {
    provinceList.value = res.data;
  });

  getStoreList({
    size: 0,
    start_page: 0
  }).then(res => {
    storeList.value = res.data;
  });

  if (route.query?.id) {
    const id = Number(route.query.id);
    getPersonList({ personnel: { id } }).then(res => {
      personInfo.value = res.data[0];
    });
  }
}

function validate() {
  let flag = true;

  for (const item of keyOnboarding) {
    if (item.keys) {
      for (const itemChild of item.keys) {
        if (itemChild.required && !personInfo.value[itemChild.key]) {
          flag = false;
          ElMessage.error(
            t("person_manage.detail.upload_required", {
              name: t(itemChild.name)
            })
          );
          return flag;
        }
      }
    }
    if (item.required && !personInfo.value[item.key] && !item.keys) {
      flag = false;
      ElMessage.error(
        t("person_manage.detail.input_required", { name: t(item.name) })
      );
      return flag;
    }
  }
  for (const item of keyDescription) {
    if (item.required && !personInfo.value[item.key]) {
      flag = false;
      ElMessage.error(
        t("person_manage.detail.input_required", { name: t(item.name) })
      );
      return flag;
    }
  }

  flag = changeHealthTime(
    personInfo.value["expiryStart"] as string,
    personInfo.value["expiryEnd"] as string
  );

  return flag;
}

function handleImgURL(url: string) {
  const isInclude = url.includes("http");
  if (!isInclude) {
    return proxyPath + url;
  }
  return url;
}

function changeHealthTime(start: string, end: string) {
  if (start && end) {
    const isAfter = dayjs(start).isAfter(dayjs(end));
    if (isAfter)
      proxy.$message.error(t("person_manage.detail.health_cert_time_error"));
    return !isAfter;
  }
}

// endregion

// region 组件事件的集合
const onSuccess = (
  rawFile: ResultProps<{
    path: string;
    relative_path: string;
    size: number;
  }>,
  key: string
) => {
  console.log(rawFile);
  personInfo.value[key] = rawFile.data.relative_path;
};

const toPrevPage = () => {
  router.go(-1);
};

const confirm = () => {
  let service = personInfo.value.id ? personUpd : personAdd;
  let accountId: string, businessId: string;
  const userInfo = localStorage.getItem(userKey);
  if (userInfo) {
    accountId = JSON.parse(userInfo).accountId;
    businessId = JSON.parse(userInfo).businessId;
  }
  console.log(personInfo.value);
  const param = {
    accountId,
    businessId,
    ...personInfo.value
  };

  if (!validate()) return;

  service(param).then(res => {
    if (res.code === 200) {
      ElMessage.success(t("notice.operation_success"));
      toPrevPage();
    }
  });
};
const cancel = () => {
  proxy.$auMessageBox
    .confirm(t("person_manage.detail.confirm_cancel"), t("notice.title"))
    .then(() => {
      toPrevPage();
    });
};

// endregion

onMounted(() => {
  init();
  console.log("import.meta?.env", import.meta?.env);
});
</script>

<style lang="scss" scoped>
.desc-item {
  :deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
    width: 165px;

    .cell-item.required {
      &::before {
        margin-right: 4px;
        color: var(--el-color-danger);
        content: "*";
      }
    }
  }

  :deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
    width: calc(40vw - 165px);
  }
}

.upload-empDocs {
  position: relative;
  height: 130px;
  border-radius: 2px;

  &::before {
    position: absolute;
    inset: 0;
    pointer-events: none; /* 确保伪元素不会影响鼠标事件 */
    content: "";
    border: 2px dashed var(--autata-border-color);
    transition: border-color 0.3s ease; /* 平滑过渡边框颜色 */
  }

  &:hover::before {
    border-color: var(--el-color-primary);
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    color: var(--el-color-primary);

    .iconfont {
      display: block;
      margin: 0 auto;
      font-size: 24px;
    }
  }
}
</style>
